package cn.com.scan.netTools;

import android.os.Handler;
import android.os.Message;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.com.scan.config.Config;

/**
 * Created by My on 2015/12/31.
 */
public class RequestWebServive extends Thread{
    String  methodName;
    String  SOAP_ACTION;
    Handler  handler;
    int TAG;
    HashMap<String,Object> map;
    public RequestWebServive(String  methodName,Handler  handler,HashMap<String,Object> map,int TAG){
        this.methodName=methodName;
        SOAP_ACTION=Config.NAMESPACE+methodName;
        this.handler=handler;
        this.map=map;
        this.TAG=TAG;
    }
    @Override
    public void run() {
        Message  message=Message.obtain();
        SoapObject rpc = new SoapObject(Config.NAMESPACE, methodName);
        Iterator<Map.Entry<String, Object>> iterator;
            if(map!=null){
            iterator = map.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry<String, Object> entry=iterator.next();
                rpc.addProperty(entry.getKey(),entry.getValue());
            }
        }
        HttpTransportSE ht = new HttpTransportSE(Config.BASEURL);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.bodyOut = rpc;
        envelope.dotNet = true;
        envelope.setOutputSoapObject(rpc);
        try {
            ht.call(SOAP_ACTION, envelope);
            // 获取返回的数据
            SoapObject object = (SoapObject) envelope.bodyIn;
            // 获取返回的结果
            String result = object.getProperty(0).toString();
            Config.LogI("result-->" + result);
            message.what=ResultCode.SUCCESS;
            message.obj=result;
            message.arg1=TAG;

        } catch (IOException e){
            if(Config.DEBUG){
                e.printStackTrace();
            }
            message.what=ResultCode.IOFAILCODE;
        } catch (XmlPullParserException e){
            if(Config.DEBUG){
                e.printStackTrace();
            }
            message.what=ResultCode.PARSERFAILCODE;
        }catch (Exception e){
            if(Config.DEBUG){
                e.printStackTrace();
            }
            message.what=ResultCode.OTHERCODE;
        }finally {
            handler.sendMessage(message);
        }

    }
}
